package sp.controller.platform;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import sp.pojo.Book;
import sp.pojo.BookCategory;
import sp.pojo.DataDict;
import sp.util.constant.SysConstant;

/**
 * 主页控制器
 * @description: 
 * @author 浮~沉
 * @date 2020年5月2日
 */


@Controller
@RequestMapping(value = "/home")
public class HomeController extends BaseController{

	
	
	/**
	 * 首页-->侧边的导航目录显示
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "home.action", method = RequestMethod.GET)
	public String homePage(Model model) throws Exception {
		log.debug("首页--->");
		LinkedHashMap<BookCategory, LinkedHashMap<BookCategory, List<BookCategory>>> Oldmap = getCategoryService().listCategoryWithMap();
		List<Book> textBookList = listBookWithCategory(53);
		List<Book> techBookList = listBookWithCategory(54);
		
		String jsonString = JSONObject.toJSONString(Oldmap, true);
		//保证顺序
		Map<BookCategory, LinkedHashMap<BookCategory, List<BookCategory>>> map = JSONObject.parseObject(jsonString, LinkedHashMap.class, Feature.OrderedField);
		
		model.addAttribute("cateGoryMap", map);
		model.addAttribute("textBookList", textBookList);
		model.addAttribute("techBookList", techBookList);
		return "platform/home";
	}
	
	
	@ResponseBody
	@RequestMapping(value = "fuzzysearch.action", method = RequestMethod.GET)
	public Map<String, Object> getFuzzyMatchResult(@RequestParam(value="searchParam", required=false) String searchParam){
		log.debug("模糊查询--->");
		Map<String, Object> resultMap = new HashMap<>();
		if (null == searchParam || !searchParam.trim().equals("")) {
			return resultMap;
		}
		
		List<Book> books = getBookService().listBookWithSearch(searchParam);
		
		resultMap.put("item", books);
		
		return resultMap;	
	}
	
	/**
	 * bookList--查询图书
	 * 同时需要回显字段
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "book/list.action", method = RequestMethod.POST)
	public String bookListPage(ModelMap mv, HttpSession session, 
			@RequestParam(value="createBy", required=false)String createBy, @RequestParam(value="isbn", required=false)String isbn, 
			@RequestParam(value="bookName", required=false)String bookName, @RequestParam(value="publish", required=false)String publish, 
			@RequestParam(value="author", required=false)String author, @RequestParam(value="condition", required=false)String condition,
			@RequestParam(value="bookStatus", required=false)String bookStatus, @RequestParam(value="bookLevel1", required=false)String bookLevel1, 
			@RequestParam(value="bookLevel2", required=false)String bookLevel2, @RequestParam(value="bookLevel3", required=false)String bookLevel3,
			@RequestParam(value="rangeIndex", required=false)String rangeIndex, @RequestParam(value="intervalStr", required=false)String intervalStr, 
			@RequestParam(value="pageIndex",required=false) String curIndex, @RequestParam(value="pageSize",required=false) String pageSize) throws Exception{
		
		log.debug("图书列表--->");
		
		//将请求参数转为整形的标识数组 	-- 对应map.key 
		String[] paramStr = {
					SysConstant.BOOK_OWNER, SysConstant.BOOK_CONDTION, SysConstant.BOOK_STATUS,
					SysConstant.BOOK_LEVEL1, SysConstant.BOOK_LEVEL2, SysConstant.BOOK_LEVEL3,
					SysConstant.RANGE_INDEX, SysConstant.CURRNET_INDEX, SysConstant.PAGESIZE
				};
		//转换为整形的请求参数数组  -- 对应map.value
		String[] params = {createBy , condition, bookStatus, bookLevel1, bookLevel2, bookLevel3, rangeIndex, curIndex, pageSize};
		//转换参数后存储的map
		HashMap<String, Integer> paramsMap = getIntegerParamsMap(paramStr, params);
		
		
		//返回前台的数据区域
		List<Book> bookList = null;
		List<DataDict> bookStatusList = getDataDictService().listDataDict(SysConstant.DICT_BOOK_STATUS);
		List<DataDict> conditionList = getDataDictService().listDataDict(SysConstant.DICT_CONDICTION);
		List<DataDict> priceRangeList = getDataDictService().listDataDict(SysConstant.DICT_PRICE_RANGE);
		
		
		//三级目录
		List<BookCategory> bookLevel1List = getCategoryService().listBookCatgorys(null);
		List<BookCategory> bookLevel2List = null;
		List<BookCategory> bookLevel3List = null;
		
		//分页
		Integer currentIndex = null;
		Integer pageSizes = null;
		if (Objects.isNull(curIndex) || ("").equals(curIndex)) {
			currentIndex = SysConstant.DEFAULT_CURRNET_INDEX;
		} else {
			currentIndex = paramsMap.get(SysConstant.CURRNET_INDEX);
		}
		
		if(Objects.isNull(pageSize) || ("").equals(pageSize)){
			pageSizes = SysConstant.DEFAULT_PAGESIZE;
		} else {
			pageSizes = paramsMap.get(SysConstant.PAGESIZE);
		}
		

		//pagehelper工具类后面必须紧跟分页的数据集
		Page<Book> pages = PageHelper.startPage(currentIndex, pageSizes);
		bookList = getBookService().listBook(
				paramsMap.get(SysConstant.BOOK_OWNER), isbn, bookName, publish, 
				author, paramsMap.get(SysConstant.BOOK_CONDTION), paramsMap.get(SysConstant.BOOK_STATUS), 
				paramsMap.get(SysConstant.RANGE_INDEX), intervalStr,
				paramsMap.get(SysConstant.BOOK_LEVEL1), paramsMap.get(SysConstant.BOOK_LEVEL2), paramsMap.get(SysConstant.BOOK_LEVEL3));

		System.out.println("分页数量:" + pages.getPages());
		
		
		if (bookList != null && bookList.size()>0 &&
				bookLevel1 != null && bookLevel2 != null && bookLevel3 != null) {
			mv.addAttribute(SysConstant.NAV_TIP, bookList.get(0).getBookLevel1Name());
		}
		
		//查询数据回显
		mv.addAttribute("bookList", bookList);
		mv.addAttribute("bookStatusList", bookStatusList);
		mv.addAttribute("bookLevel1List", bookLevel1List);
		mv.addAttribute("conditionList", conditionList);
		mv.addAttribute("priceRangeList", priceRangeList);
	
		mv.addAttribute("pages", pages);
		mv.addAttribute("isbn", isbn);
		mv.addAttribute("bookName", bookName);
		mv.addAttribute("publish", publish);
		mv.addAttribute("author", author);
		mv.addAttribute("rangeIndex", rangeIndex);
		mv.addAttribute("condition", paramsMap.get(SysConstant.BOOK_CONDTION));
		mv.addAttribute("bookStatus", paramsMap.get(SysConstant.BOOK_STATUS));
		mv.addAttribute("bookLevel1", paramsMap.get(SysConstant.BOOK_LEVEL1));
		mv.addAttribute("bookLevel2", paramsMap.get(SysConstant.BOOK_LEVEL2));
		mv.addAttribute("bookLevel3", paramsMap.get(SysConstant.BOOK_LEVEL3));
		
		if(bookLevel2 != null && !("").equals(bookLevel2)){
			bookLevel2List = getCategoryService().listBookCatgorys(paramsMap.get(SysConstant.BOOK_LEVEL1));
			mv.addAttribute("bookLevel2List", bookLevel2List);	
		}

		if(bookLevel3 != null && !("").equals(bookLevel3)){
			bookLevel3List = getCategoryService().listBookCatgorys(paramsMap.get(SysConstant.BOOK_LEVEL2));
			mv.addAttribute("bookLevel3List", bookLevel3List);	
		}
		
		
		return "platform/book/bookList";
	}
		
	
	/**
	 * 获得更多
	 * 
	 * 改进: 由于主页已经存在该分类的信息,不应该在去查询db 
	 * 	可以考虑通过ajax直接请求
	 * @param map
	 * @param cid
	 * @return
	 */
	@RequestMapping(value = "{cid}/more.action", method = RequestMethod.GET)
	public String morePage(ModelMap map, @PathVariable("cid") String cid,
				@RequestParam(value = "curIndex", required=false) String curIndex, @RequestParam(value="pageSize", required=false)String pageSize) {
		log.debug("教材-->详情页:"+cid);
		if(("").equals(cid)) cid = null;
		Integer id = null;
		try{
			id = Integer.valueOf(cid);
		} catch (NumberFormatException e) {
			log.debug("服务器无法识别该目录");
		}
		
		//分页
		Integer currentIndex = null;
		Integer pageSizes = null;
		if (Objects.isNull(curIndex) || ("").equals(curIndex)) {
			currentIndex = SysConstant.DEFAULT_CURRNET_INDEX;
		} else {
			currentIndex = Integer.valueOf(curIndex);
		}
		
		if(Objects.isNull(pageSize) || ("").equals(pageSize)){
			pageSizes = SysConstant.DEFAULT_PAGESIZE;
		} else {
			pageSizes = Integer.valueOf(pageSize);
		}
		
		
		Page<Book> pages = PageHelper.startPage(currentIndex, pageSizes);
		List<Book> listBook = listBookWithCategory(id);
		
		//导航指示信息  显示一级目录
		map.put(SysConstant.NAV_TIP, listBook.get(0).getBookLevel1Name());
		map.put("bookList", listBook);
		map.put("pages", pages);
		map.put("cid", cid);

		return "platform/more";
	}
	
	
	
	
	/**
	 * 根据类别统一查询book列表
	 * @param params  对应三级目录的id
	 * @return
	 */
	private List<Book> listBookWithCategory(Integer ...params) {
		if (params == null || params.length == 0) return null;
		try {
			//要么只有第1级 要么都有
			if (params.length == 1) {
				return getBookService().listBook(null, null, null, null, null, null, null, null, null, params[0], null, null);
			} else  
				return getBookService().listBook(null, null, null, null, null, null, null, null, null, params[0], params[1], params[2]);		
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
	}
	
	
	/**
	 * 将请求参数转为整形后  存储在map中
	 * 便于统一异常处理 和 获取
	 * @param paramStr map.key
	 * @param params  map.value
	 * @return value值为Integer的map
	 */
	private HashMap<String, Integer> getIntegerParamsMap(String[] paramStr, String[] params) {
		HashMap<String, Integer> paramMap = new HashMap<>();
		
		if(Objects.isNull(params) || params.length == 0) 
			return paramMap;
		//key 和 value 长度必须对应
		if(paramStr.length != params.length)
			return paramMap;
		
		for (int i = 0; i < paramStr.length; i++) {
			if(!Objects.isNull(params[i]) && !("").equals(params[i])){
				try {
					Integer newParam = Integer.valueOf(params[i].trim());
					paramMap.put(paramStr[i], newParam);
				} catch (NumberFormatException e) {
					throw new NumberFormatException(paramStr[i]+"输入类型不匹配, 请检查后再试!");
				}
			}
		}
		
		return paramMap;
	}
}
